import { NextRequest, NextResponse } from "next/server";
import fs from "fs";
import path from "path";
import { promises as fsPromises } from "fs";
import { v4 as uuidv4 } from "uuid";

// 数据目录
const DATA_DIR = path.join(process.cwd(), "data", "memories");

// 确保数据目录存在
async function ensureDataDir() {
  try {
    await fsPromises.access(DATA_DIR);
  } catch (error) {
    await fsPromises.mkdir(DATA_DIR, { recursive: true });
  }
}

// 读取内存数据
async function getMemories(source?: string, exam?: string, examDate?: string, grade?: string, isInternational?: boolean) {
  await ensureDataDir();
  
  try {
    const files = await fsPromises.readdir(DATA_DIR);
    const jsonFiles = files.filter(file => file.endsWith(".json"));
    
    const memories: any[] = [];
    
    for (const file of jsonFiles) {
      const filePath = path.join(DATA_DIR, file);
      const content = await fsPromises.readFile(filePath, "utf-8");
      const memory = JSON.parse(content);
      
      // 首先检查国际化标志是否匹配
      // 如果请求国际版，只返回有international=true的记忆
      // 如果请求中文版，只返回没有international标志或international=false的记忆
      if (isInternational) {
        if (!memory.international) continue;
      } else {
        if (memory.international) continue;
      }
      
      // 接着检查exam是否匹配 - 这是必须的条件
      const matchExam = !exam || memory.exam === exam;
      if (!matchExam) continue; // 如果exam不匹配，直接跳过这条记录
      
      // 其他字段作为进一步筛选条件，只有当记录中存在该字段且传入了对应参数时才进行判断
      const matchSource = !source || !('source' in memory) || memory.source === source;
      const matchExamDate = !examDate || !('examDate' in memory) || memory.examDate === examDate;
      const matchGrade = !grade || !('grade' in memory) || memory.grade === grade;
      
      // 所有启用的筛选条件都必须匹配
      if (matchSource && matchExamDate && matchGrade) {
        memories.push(memory);
      }
    }
    
    // 按时间戳降序排序（最新的在前）
    return memories.sort((a, b) => 
      new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
    );
  } catch (error) {
    console.error("读取回忆数据时出错:", error);
    return [];
  }
}

// 保存回忆数据
async function saveMemory(data: any) {
  await ensureDataDir();
  
  const id = uuidv4();
  const timestamp = new Date().toISOString();
  const fileName = `memory_${id}.json`;
  const filePath = path.join(DATA_DIR, fileName);
  
  const memoryData = {
    id,
    fileName,
    timestamp,
    ...data
  };
  
  await fsPromises.writeFile(filePath, JSON.stringify(memoryData, null, 2), "utf-8");
  return memoryData;
}

// GET 处理程序 - 获取回忆数据
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const source = searchParams.get("source") || undefined;
    const exam = searchParams.get("exam") || undefined;
    const examDate = searchParams.get("examDate") || undefined;
    const grade = searchParams.get("grade") || undefined;
    const isInternational = searchParams.get("int") === "true";
    
    // 如果提供了年级和考试名称，使用统一格式构建查询
    let formattedExam = exam;
    if (exam && grade && !exam.startsWith(`${grade} `)) {
      formattedExam = `${grade} ${exam}`;
      console.log(`使用格式化的考试名称进行查询: ${formattedExam}`);
    }
    
    const memories = await getMemories(source, formattedExam, examDate, grade, isInternational);
    
    console.log(`找到 ${memories.length} 条记忆记录，国际版: ${isInternational}`);
    if (memories.length > 0) {
      console.log("第一条记录:", {
        exam: memories[0].exam,
        examDate: memories[0].examDate,
        grade: memories[0].grade,
        international: memories[0].international
      });
    }
    
    return NextResponse.json({ memories });
  } catch (error) {
    console.error("处理GET请求时出错:", error);
    return NextResponse.json({ error: "处理请求时出错" }, { status: 500 });
  }
}

// POST 处理程序 - 添加新回忆
export async function POST(request: NextRequest) {
  try {
    const data = await request.json();
    
    // 验证请求数据
    if (!data.exam || !data.questions || !data.questions.trim()) {
      return NextResponse.json(
        { error: "缺少必要的字段" },
        { status: 400 }
      );
    }
    
    // 获取international参数
    const url = new URL(request.url);
    const isInternational = url.searchParams.get("int") === "true" || data.international === true;
    
    // 处理并保存数据
    const memoryData = {
      exam: data.exam,
      examDate: data.examDate || "", // 添加考试日期
      grade: data.grade || "",       // 添加年级
      source: data.source || "未知来源",
      questions: data.questions,
      signature: data.signature || "匿名用户",
      international: isInternational // 保存国际化标志
    };
    
    const savedMemory = await saveMemory(memoryData);
    return NextResponse.json(savedMemory, { status: 201 });
  } catch (error) {
    console.error("处理POST请求时出错:", error);
    return NextResponse.json({ error: "处理请求时出错" }, { status: 500 });
  }
} 